﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YBApproval.IDAL;
using YBApproval.Model;

namespace YBApproval.EFDAL
{
    public class NodeDAL: INode
    {
        private YBDbContext _db = new YBDbContext();

        public Node GetNode(int nodeId)
        {
            return _db.Nodes.Find(nodeId);
        }

        /// <summary>
        /// 获取该process的下一个node
        /// </summary>
        /// <param name="processId">流程编号</param>
        /// <param name="order">顺序号</param>
        /// <returns>找到则Node实例，没找到则返回null</returns>
        public Node GetNextNode(int processId, int order)
        {
            var query = from n in _db.Nodes
                        where n.ProcessId == processId && n.Order > order
                        orderby n.Order
                        select n;

            if (query != null && query.Count() > 0)
            {
                return query.First<Node>();
            }
            else
            {
                return null;
            }
        }

        public Node GetPreNode(int processId, int order)
        {
            var query = from n in _db.Nodes
                        where n.ProcessId == processId && n.Order < order
                        orderby n.Order descending
                        select n;

            if (query != null && query.Count() > 0)
            {
                return query.First<Node>();
            }
            else
            {
                return null;
            }
        }

        public Node GetCurrentNode(int processId, int order)
        {
            var query = from n in _db.Nodes
                        where n.ProcessId == processId && n.Order == order
                        orderby n.Order descending
                        select n;

            if (query != null && query.Count() > 0)
            {
                return query.First<Node>();
            }
            else
            {
                return null;
            }
        }

        public void Dispose()
        {
            _db.Dispose();
        }
    }
}
